const path = require('path');
const { VueLoaderPlugin } = require('vue-loader');
const glob = require('glob');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

const entryFiles = glob.sync('./package/**/index.js');
const entrys = {};

entryFiles.forEach((file) => {
  const res = file.match(/package\\(.*)\\index\.js/); // windows 下正则匹配
  entrys[res[1]] = {
    import: `./${res[0]}`,
  };
});
console.log('entrys', entrys);
module.exports = {
  mode: 'production',
  entry: entrys,
  output: {
    path: path.resolve(__dirname, 'card'), // 输出路径
    filename: '[name].js',
    library: '[name]Lib',
    libraryTarget: 'umd',
    umdNamedDefine: true,
    clean: true,
    globalObject: 'this', // 兼容性设置，适用于多种环境
  },
  externals: ['vue', 'element-plus', 'pinia', 'axios', 'moment-timezone'],
  // externals: ['vue'],
  resolve: {
    mainFiles: ['index', 'default'], // 注意，这个index必须要有，否则会报错
    alias: {
      '@': path.resolve(__dirname, 'src'), // Add alias for "@" to resolve from the src directory
    },
    // 配置省略文件路径的后缀名 'xxx.js'->'xxx'
    // 使用这个配置时切记不可以起名字相同的文件，比如index.js和index.css,那么在引入index.css的时候可能会引成index.js
    extensions: ['.js', '.json', '.jsx', '.css'],
  },
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
        },
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.less$/,
        use: [
          'style-loader', // 将编译后的CSS以<style>标签的形式插入到HTML中
          'css-loader', // 处理CSS文件
          'less-loader', // 处理Less文件并将其编译成CSS
        ],
      },
      {
        test: /\.(png|jpe?g|gif|webp)$/,
        type: 'asset',
        parser: {
          dataUrlCondition: {
            maxSize: 4 * 1024 * 1024, // 小于4kb的图片会被base64处理
          },
        },
      },
    ],
  },
  plugins: [
    new VueLoaderPlugin(), // 添加 VueLoaderPlugin 插件
    new CleanWebpackPlugin({
      cleanOnceBeforeBuildPatterns: [path.join(__dirname, 'dist/card/*')],
    }),
  ],
  stats: {
    children: true, // 启用子编译的详细信息
  },
};
